//
//  MessageManager.m
//  Message
//
//  Created by Fanty on 13-12-17.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "MessageManager.h"
#import "MessageParser.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "ApiConstant+Cube.h"
#import <chameleon-ios-sdk/CApplication.h>
#import <AudioToolbox/AudioToolbox.h>

#import <chameleon-ios-sdk/Library/SqliteDB.h>
#import <chameleon-ios-sdk/Library/SqliteResultSet.h>
#import <chameleon-ios-sdk/DBStorageHelper.h>
#import "DataCenter+Cube.h"
#import "CubesModel.h"
#import <MainModuleSDK/MainModule.h>
#import <MainModuleSDK/AsyncTask.h>
#import "MessageModel.h"
#import "BSLCubeConstant.h"
#import <chameleon-ios-sdk/RoutingParserHelper.h>

@interface MessageManager()

-(void)startTimer:(BOOL)callNow;

-(void)sendFeedBack:(NSArray*)array;

-(BOOL)fillMessageLists:(NSArray*)list;

-(void)syncFinish:(BOOL)apnsNotify;

@end

@implementation MessageManager{
    AsyncTask* task;
    NSTimer* timer;
    
    CFURLRef soundFileURLRef;
    SystemSoundID soundFileObject;
    
}


-(id)init{
    self=[super init];
    if(self){
        NSURL *tapSound = [NSURL URLWithString:@"/System/Library/Audio/UISounds/sms-received1.caf"];
        soundFileURLRef = (CFURLRef) CFBridgingRetain(tapSound);
        AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject);
        
    }
    return self;
}


-(void)cancel{
    [task cancel];
    task=nil;
    [timer invalidate];
    timer=nil;
}

-(void)syncUpdateNumber{
    //    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Module"];
    //    data.identifier=username;
    SqliteDB* database=[data openDatabase];
    [database open];
    SqliteResultSet* resultSet=[database executeQuery:@"select * from message"];
    
    MessageModel* messageModel=[[MessageModel alloc] init];
    while([resultSet next]){
        messageModel.isRead=[resultSet boolForColumn:@"isRead"];
        messageModel.moduleIdentifer=[resultSet stringForColumn:@"moduleIdentifer"];
        messageModel.moduleBadge=[resultSet intForColumn:@"moduleBadge"];
        if(!messageModel.isRead){
            if([messageModel.moduleIdentifer length]>0){
                CubeModel* cubeModel=[[DataCenter defaultCenter] finidServiceCubeModule:messageModel.moduleIdentifer];
                if([messageModel.moduleIdentifer isEqualToString:@"com.foss.message.record"])
                    cubeModel.unReadCount++;
                else{
                    cubeModel.moduleBadge = messageModel.moduleBadge;
                    if(cubeModel.moduleBadge){
                        cubeModel.unReadCount++;
                    }
                }
            }
        }
    }
    [resultSet close];
    [database close];
    
}


-(void)syncMessage{
    [self cancel];
    MainModule* mainModule=(MainModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Main"];
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[[ApiConstant defaultConstant] messageListURL]];
    task=[mainModule asyncWithOperation:request parser:[[MessageParser alloc] init]];
    __block MessageManager* objSelf=self;
    [task setFinishBlock:^{
        [objSelf syncFinish:NO];
        
    }];
}

-(void)syncMessageById:(NSString*)messageId routing:(BOOL)routing{
    [self cancel];
    MainModule* mainModule=(MainModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Main"];
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[[ApiConstant defaultConstant] messageByIdURL:messageId]];
    task=[mainModule asyncWithOperation:request parser:[[MessageParser alloc] init]];
    __block MessageManager* objSelf=self;
    [task setFinishBlock:^{
        [objSelf syncFinish:routing];
    }];
    
}

-(void)syncFinish:(BOOL)apnsNotify{
    NSArray* list=[task result];
    task=nil;
    if ([list count] > 0){
        BOOL existSecurity=[self fillMessageLists:list];
        if(existSecurity){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Cube_SecurityUpdated" object:nil];
        }
        [self sendFeedBack:list];
        [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleUpdateIconNumber object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Cube_MessageUpdated" object:nil];
        
        if(apnsNotify){
            [self checkApnsRedirectAndRedirect:[list objectAtIndex:0] routingByMessageRecord:NO];
        }
    }
    else{
        [self startTimer:NO];
    }
}

-(void)checkApnsRedirectAndRedirect:(MessageModel*)messageModel routingByMessageRecord:(BOOL)routingByMessageRecord{
    
    NSString* moduleIdentifier=nil;
    
    NSString* pageIdentifier=nil;
    NSMutableDictionary* params=[[NSMutableDictionary alloc] initWithCapacity:2];
    
    if([messageModel.messageType isEqualToString:@"SYS"] || [messageModel.messageType isEqualToString:@"SECURITY"]){
        moduleIdentifier=@"Module";
        pageIdentifier=@"MessageViewController";
    }
    else{
        //判断该模块是否已经有安装 ，没有安装就直接跳去系统模块
        if(![[DataCenter defaultCenter] finidInstallCubeModule:messageModel.moduleIdentifer]){
            moduleIdentifier=@"Module";
            pageIdentifier=@"MessageViewController";
        }
        else{
            //先找出是否有该模块标识所隶属的原生工程模块，  如果没有则为html模块
            moduleIdentifier=[[RoutingParserHelper sharedRouting] moduleIdentifierForLink:messageModel.moduleUrl identifier:messageModel.moduleIdentifer];
            if(moduleIdentifier==nil){     //没有，则为html5 模块
                [params setObject:@"1" forKey:@"html5Module"];
                moduleIdentifier=@"Module";
                pageIdentifier=messageModel.moduleIdentifer;
                if([messageModel.moduleUrl length]>0)
                    [params setObject:messageModel.moduleUrl forKey:@"moduleUrl"];
                
            }
            else{
                NSString* moduleUrl=messageModel.moduleUrl;
                if([moduleUrl length]<1)
                    moduleUrl=@"/index";
                pageIdentifier=[[RoutingParserHelper sharedRouting] pageIdentifierForLink:moduleUrl identifier:messageModel.moduleIdentifer outParams:params];
                if([pageIdentifier length]<1){
                    [params removeAllObjects];
                    moduleUrl=@"/index";
                    pageIdentifier=[[RoutingParserHelper sharedRouting] pageIdentifierForLink:moduleUrl identifier:messageModel.moduleIdentifer outParams:params];
                }
            }
        }
    }
    
    if(routingByMessageRecord){
        [params setObject:[NSNumber numberWithBool:YES] forKey:@"routingByMessageRecord"];
    }
    
    NSDictionary* dict=[[NSDictionary alloc] initWithObjectsAndKeys:
                        moduleIdentifier,@"moduleIdentifier",
                        pageIdentifier,@"identifier",
                        params,@"params",
                        nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:CubeAPNSPushModuleWeb object:dict];
    
}

-(NSArray*)messageGroupList{
    
    
    //    DataCenter* dataCenter=[DataCenter defaultCenter];
    
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Module"];
    //    data.identifier=dataCenter.username;
    SqliteDB* database=[data openDatabase];
    [database open];
    
    SqliteResultSet* resultSet=[database executeQuery:@"select moduleIdentifer,moduleName,isRead from Message"];
    
    NSMutableArray* array=[[NSMutableArray alloc] initWithCapacity:2];
    while([resultSet next]){
        MessageGroupModel* model=nil;
        NSString* moduleIdentifer=[resultSet stringForColumnIndex:0];
        for(MessageGroupModel* _model in array){
            if([_model.moduleIdentifer isEqualToString:moduleIdentifer]){
                model=_model;
                break;
            }
        }
        if(model==nil){
            model=[[MessageGroupModel alloc] init];
            [array addObject:model];
        }
        model.moduleIdentifer=moduleIdentifer;
        model.moduleName=[resultSet stringForColumnIndex:1];
        BOOL isRead=[resultSet boolForColumnIndex:2];
        if(!isRead)
            model.unReadCount++;
        model.totalCount++;
        
    }
    [resultSet close];
    return array;
}

-(NSArray*)messageList:(NSString*)moduleIdentifier{
    
    NSMutableArray* array=[[NSMutableArray alloc] initWithCapacity:2];
    
    //    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Module"];
    //    data.identifier=username;
    SqliteDB* database=[data openDatabase];
    [database open];
    SqliteResultSet* resultSet=[database executeQuery:[NSString stringWithFormat:@"select * from message where moduleIdentifer='%@' order by rowid desc",moduleIdentifier]];
    
    [database setDateFormat:[SqliteDB storeableDateFormat:@"yyyy-MM-dd hh:mm:ss +000"]];
    
    //2013-12-25 02:54:41 +0000
    while([resultSet next]){
        MessageModel* messageModel=[[MessageModel alloc] init];
        messageModel.messageId=[resultSet stringForColumn:@"id"];
        messageModel.title=[resultSet stringForColumn:@"title"];
        messageModel.content=[resultSet stringForColumn:@"content"];
        messageModel.messageType=[resultSet stringForColumn:@"messageType"];
        messageModel.receiveTime=[resultSet dateForColumn:@"receiveTime"];
        messageModel.isRead=[resultSet boolForColumn:@"isRead"];
        messageModel.moduleIdentifer=[resultSet stringForColumn:@"moduleIdentifer"];
        messageModel.moduleName=[resultSet stringForColumn:@"moduleName"];
        messageModel.announceId=[resultSet stringForColumn:@"announceId"];
        messageModel.moduleBadge=[resultSet intForColumn:@"moduleBadge"];
        messageModel.busiDetail=[resultSet intForColumn:@"busiDetail"];
        messageModel.moduleUrl=[resultSet stringForColumn:@"moduleUrl"];
        
        [array addObject:messageModel];
        
        //暂时先这样，到时加返load more
        if([array count]>=200)break;
    }
    [resultSet close];
    [database close];
    
    return array;
}

-(void)removeMesageById:(MessageModel*)messageModel{
    //    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Module"];
    //    data.identifier=username;
    SqliteDB* database=[data openDatabase];
    [database open];
    
    [database executeUpdate:[NSString stringWithFormat:@"delete from message where id='%@' ",messageModel.messageId]];
    [database close];
    
    if(!messageModel.isRead){
        CubeModel* cubeModel=[[DataCenter defaultCenter] finidServiceCubeModule:messageModel.moduleIdentifer];
        cubeModel.unReadCount--;
        if(cubeModel.unReadCount<1)
            cubeModel.unReadCount=0;
        [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleUpdateIconNumber object:nil];
    }
}

-(void)removeMessageByGroup:(NSString*)moduleIdentifier{
    //    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Module"];
    //    data.identifier=username;
    SqliteDB* database=[data openDatabase];
    [database open];
    [database executeUpdate:[NSString stringWithFormat:@"delete from message where moduleIdentifer='%@' ",moduleIdentifier]];
    [database close];
    
    CubeModel* cubeModel=[[DataCenter defaultCenter] finidServiceCubeModule:moduleIdentifier];
    cubeModel.unReadCount=0;
    [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleUpdateIconNumber object:nil];
    
}

-(void)setIsReadMessageById:(MessageModel*)messageModel{
    //    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Module"];
    //    data.identifier=username;
    SqliteDB* database=[data openDatabase];
    [database open];
    [database executeUpdate:[NSString stringWithFormat:@"update message set isRead=1 where id='%@' ",messageModel.messageId]];
    [database close];
    
    CubeModel* cubeModel=[[DataCenter defaultCenter] finidServiceCubeModule:messageModel.moduleIdentifer];
    cubeModel.unReadCount--;
    if(cubeModel.unReadCount<1)
        cubeModel.unReadCount=0;
    [[NSNotificationCenter defaultCenter] postNotificationName:CubeModuleUpdateIconNumber object:nil];
    
}

-(void)startTimer:(BOOL)callNow{
    [self cancel];
    timer=[NSTimer scheduledTimerWithTimeInterval:(callNow?3.0f:300.0f) target:self selector:@selector(syncMessage) userInfo:nil repeats:NO];
}

-(void)sendFeedBack:(NSArray*)array{
    [self cancel];
    
    NSMutableString* ids=[[NSMutableString alloc] initWithCapacity:2];
    [array enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL*stop){
        MessageModel* model=obj;
        [ids appendString:model.messageId];
        if(index<[array count]-1)
            [ids appendString:@","];
        
    }];
    
    MainModule* mainModule=(MainModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Main"];
    ASIFormDataRequest* request=[mainModule requestWithURL:[[ApiConstant defaultConstant] receptURL]];
    request.timeOutSeconds=5.0f;
    request.persistentConnectionTimeoutSeconds=5.0f;
    
    [request setPostValue:ids  forKey:@"msgId"];
    [request setPostValue:[ApiConstant defaultConstant].appKey forKey:@"appId"];
    [request setRequestMethod:@"PUT"];
    
    task=[mainModule asyncWithOperation:request parser:nil];
    __block MessageManager* objSelf=self;
    [task setFinishBlock:^{
        
        [objSelf startTimer:YES];
        
    }];
}

-(BOOL)fillMessageLists:(NSArray*)list{
    
    BOOL existsSecurity=NO;
    BOOL activateSound=NO;
    //    DataCenter* dataCenter=[DataCenter defaultCenter];
    
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Module"];
    //    data.identifier=dataCenter.username;
    SqliteDB* database=[data openDatabase];
    [database open];
    
    NSDate* date=[NSDate date];
    [database beginTransaction];
    
    
    
    for(MessageModel* model in list){
        model.receiveTime=date;
        if ([model.messageType isEqualToString:@"SYS"])       //系统消息的话，提供一个identifier给它
        {
            model.moduleIdentifer = @"com.foss.message.record";
        }
        else if ([model.messageType isEqualToString:@"SECURITY"])       //权限更改的话，提供一个identifier给它
        {
            model.moduleIdentifer = @"com.foss.message.record";
        }
        @autoreleasepool {

            NSString* sql=[NSString stringWithFormat:@"insert into Message(id,title,content,messageType,receiveTime,isRead,moduleIdentifer,moduleName,announceId,moduleBadge,busiDetail,moduleUrl) values(?,?,?,?,datetime('now'),0,?,?,?,%d,%d,?)",model.moduleBadge,model.busiDetail];
            
            if([database executeUpdate:sql,model.messageId,model.title,model.content,model.messageType,model.moduleIdentifer,model.moduleName,model.announceId,model.moduleUrl]){
                activateSound=YES;
                if([model.moduleIdentifer length]>0){
                    CubeModel* cubeModel=[[DataCenter defaultCenter] finidServiceCubeModule:model.moduleIdentifer];
                    cubeModel.unReadCount++;
                    cubeModel.moduleBadge = model.moduleBadge;
                }
                if(!existsSecurity && [model.messageType isEqualToString:@"SECURITY"]){
                    existsSecurity=YES;
                }
            }
        }
        
    }
    [database commit];
    [database close];
    
    if(activateSound)
        AudioServicesPlayAlertSound(soundFileObject);
    
    
    return existsSecurity;
}



@end
